package xcmg.device.infra;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import yb.ecp.fast.dto.UserDetailDTO;
import yb.ecp.fast.feign.AuthClient;
import yb.ecp.fast.infra.infra.ActionResult;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by john on 2017/4/11.
 */
@Slf4j
public class BasicController {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AuthClient authClient;

    public <T> ActionResult<T> actionResult(ErrorCode code, T value) {
        return new ActionResult<T>(code.getCode(),
                code.getDesc(),
                value);
    }

    public <T> ActionResult<T> actionResult(ErrorCode code, String errorMsg, T value) {

        return new ActionResult<T>(code.getCode(),
                errorMsg,
                value);
    }

    public boolean successActionResult(ActionResult result) {
        if (result == null) {
            return false;
        }
        int code = result.getCode();
        return code == ErrorCode.Success.getCode();
    }

    public <T> ActionResult<T> actionValueResult(T value) {
        ErrorCode code = ErrorCode.Success;

        return actionResult(code, value);
    }

    public ActionResult<String> actionResult(ErrorCode code) {
        if (code == null) {
            code = ErrorCode.Success;
        }
        return actionResult(code, code.getDesc());
    }

    public String getUserId(HttpServletRequest request) {
        return request.getHeader("x-user-id");
    }

//    public Map getLoginUserInfo(String userId) {
//        ActionResult login = authClient.getLogin(userId);
//        return (Map) login.getValue();
//    }


    public String getUserId() {
        String userId = request.getHeader("x-user-id");
        if (StringUtils.isNotBlank(userId)) {
            return userId;
        }
        throw new RuntimeException("获取用户信息失败");
    }

    public String getCustomerId() throws Exception {
        String userId = request.getHeader("x-user-id");
        if (StringUtils.isBlank(userId)) {
            throw new Exception("获取小程序登陆信息失败");
        }
        return userId;
    }

    /**
     * 查询orgId（workspaceId==orgId）
     *
     * @return String
     * @throws Exception Exception
     */
    public String getOrgId() throws Exception {
        String userId = getUserId();
        ActionResult<String> actionResult = authClient.queryWorkspaceId(userId);
        if (!successActionResult(actionResult)) {
            throw new Exception("获取组织ID失败");
        }
        return actionResult.getValue();
    }

    private UserDetailDTO getUserDetailSafe(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        try {
            ActionResult<UserDetailDTO> result = authClient.getUserDetail(userId);
            if (successActionResult(result)) {
                return result.getValue();
            }
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
        }
        return null;
    }

    public String getUserName() {
        String userId = getUserId();
        UserDetailDTO userInfo = getUserDetailSafe(userId);
        return (userInfo != null) ? userInfo.getName() : userId;
    }

    public String getDeptName() {
        String userId = getUserId();
        UserDetailDTO userInfo = getUserDetailSafe(userId);
        if (userInfo != null) {
            return userInfo.getDeptName();
        }
        throw new RuntimeException("部门名称获取失败");
    }

    public String getDeptId() throws Exception {
        String userId = getUserId();
        UserDetailDTO userInfo = getUserDetailSafe(userId);
        if (userInfo != null) {
            return userInfo.getDeptId();
        }
        throw new Exception("部门ID获取失败");
    }

    public <T> ActionResult actionResultWithBindingResult(ErrorCode code, BindingResult bindingResult) {
        String errMsg = getBindingResultErrors(bindingResult);
        if (StringUtils.isBlank(errMsg)) {
            return actionResult(code);
        }
        return actionResultDesc(code, errMsg);
    }

    public String getBindingResultErrors(BindingResult bindingResult) {
        if (null == bindingResult || !bindingResult.hasErrors()) {
            return StringUtils.EMPTY;
        }
        StringBuilder errorStrBuilder = new StringBuilder();
        List<ObjectError> errorList = bindingResult.getAllErrors();
        for (ObjectError error : errorList) {
            errorStrBuilder.append(error.getDefaultMessage()).append(";");
        }
        return StringUtils.removeEnd(errorStrBuilder.toString(), ";");
    }

    public <T> ActionResult<T> actionResultDesc(ErrorCode code, T value) {
        if (code != ErrorCode.Success
                && value != null
                && StringUtils.isNotBlank(value.toString())) {
            return new ActionResult<>(code.getCode(),
                    value.toString(),
                    value);
        }
        return new ActionResult<>(code.getCode(),
                code.getDesc(),
                value);
    }
}
